package cn.tedu.order.service;

import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.Order;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RocketMQTransactionListener
@Service
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private TxMapper txMapper;

    @Override
    public void create(Order order) {

        String xid = UUID.randomUUID().toString().replace("-", "");

        AccountMessage am = new AccountMessage(
                order.getUserId(),
                order.getMoney(),
                xid);
        String json = JsonUtil.to(am);
        Message<String> msg = MessageBuilder.withPayload(json).build();

        rocketMQTemplate.sendMessageInTransaction(
                "orderTopic",
                msg,
                order);

    }

    public void doCreate(Order order) {

        //远程调用发号器生成订单id (发号器)
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        // 临时随机生成一个id，添加发号器后删除该段(Math.abs取绝对值)
        // long orderId = Math.abs(new Random().nextLong());
        order.setId(orderId);
        orderMapper.create(order);

        // 远程调用库存减少商品库存
        //storageClient.decrease(order.getProductId(), order.getCount());
        // 远程调用账户扣减账户金额
        //accountClient.decrease(order.getUserId(), order.getMoney());

    }

    // 执行本地事务
    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        // 数据表状态0,1
        int status;
        RocketMQLocalTransactionState state;
        try {
            Order order = (Order) o;
            status = 0;
            state = RocketMQLocalTransactionState.COMMIT;
            doCreate(order);
        } catch (Exception e) {
            log.error("本地事务存储订单失败",e);
            status = 1;
            state = RocketMQLocalTransactionState.ROLLBACK;
        }

        // 事务状态存储到数据表 tx_table
        Object payload = message.getPayload();
        String json = new String((byte[]) payload);
        String xid = JsonUtil.getString(json, "xid");


//        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
//        Date date = new Date();
//        String created = dateFormat.format(date);

        txMapper.insert(new TxInfo(xid, status, System.currentTimeMillis()));

        return state;
    }

    // 处理事务状态回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        Object payload = message.getPayload();
        String json = new String((byte[]) payload);
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo == null) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()) {
            case 0: return RocketMQLocalTransactionState.COMMIT;
            case 1: return RocketMQLocalTransactionState.ROLLBACK;
            default: return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
